package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"go-interview-forum/pkg"
	"net/http"
)

// 中间件函数写法
func TokenAuth(c *gin.Context) {
	token := c.GetHeader("Authorization")
	if token == "" {
		c.JSON(http.StatusUnauthorized, gin.H{})
		c.Abort()
		return
	}

	var userId string
	userId, err := pkg.ParseJwtToken(token, viper.GetString("jwt.secret"))
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{})
		c.Abort()
	}

	c.Set("userId", userId)
}
